package cn.topcodes.tcsf.admin.web.controller.impl;

import cn.topcodes.tcsf.admin.commons.api.security.ShiroUtil;
import cn.topcodes.tcsf.admin.commons.api.domain.ApiResponseEntity;
import cn.topcodes.tcsf.admin.commons.api.controller.generic.GenericApiController;
import cn.topcodes.tcsf.admin.domain.entity.SysFile;
import cn.topcodes.tcsf.admin.domain.entity.SysUser;
import cn.topcodes.tcsf.admin.service.SysFileService;
import cn.topcodes.tcsf.admin.service.org.SysUserService;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpStatus;
import org.apache.shiro.util.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.persistence.EntityNotFoundException;
import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;

/**
 * @author Unicorn
 * @date 2017/4/21
 */
@Controller
@RequestMapping("/admin/sys-file")
public class FileAdminController extends GenericApiController<SysFile,SysFile,SysFile> {

    @Autowired
    private SysFileService sysFileService;

    @Autowired
    private SysUserService sysUserService;

    @RequestMapping(value = "",method = RequestMethod.GET)
    public String index() {
        return "admin/file/index";
    }

    @RequestMapping(value = "upload",method = RequestMethod.GET)
    public String upload() {
        return "admin/file/upload";
    }

    /*文件上传*/
    /*@RequestMapping(value = "upload",method = RequestMethod.POST)
    public void upload(
            @RequestParam(required = true) String uuid,
            @RequestParam(required = true) int chunks,
            @RequestParam(required = true) int chunk,
            @RequestParam(required = true) MultipartFile file,
            @RequestParam(required = true) String md5
        ) throws IOException {
        this.sysFileService.saveFile(uuid,chunks,chunk,file.getInputStream(),
                file.getOriginalFilename(),file.getSize(),file.getContentType(),md5);
    }*/

    @ResponseBody
    @RequestMapping(value = "upload",method = RequestMethod.POST)
    public ApiResponseEntity upload(
            @RequestParam(required = true) MultipartFile file
        ) throws IOException {
        this.sysFileService.saveFile(file.getInputStream(), file.getSize(), file.getOriginalFilename(),file.getContentType());
        return ApiResponseEntity.buildOK();
    }

    /*文件下载*/
    @RequestMapping(value = "download",method = RequestMethod.GET)
    public void download(
            @RequestParam(required = true) Long id,
            HttpServletResponse response) throws IOException {
        SysFile fileInfo = this.sysFileService.findOne(id);
        Assert.notNull(fileInfo);
        InputStream in = null;
        try {
            in = this.sysFileService.readFile(id);
            response.reset();
            String filename = URLEncoder.encode(fileInfo.getFileName(), "UTF-8");
            response.addHeader("Content-Disposition", "attachment;filename=" + filename);
            response.addHeader("Content-Length", "" + fileInfo.getSize());
            IOUtils.copy(in, response.getOutputStream());
        }catch(FileNotFoundException e) {
            response.sendError(HttpStatus.SC_NOT_FOUND, "文件不存在");
        }finally {
            if(in != null) {
                in.close();
            }
        }
    }

    @Override
    protected boolean validateOperation(String password) {
        Long userId = ShiroUtil.getUserId();
        SysUser user = this.sysUserService.findOne(userId);
        if(user == null) {
            throw new EntityNotFoundException("管理用户不存在");
        }
        return this.sysUserService.isPwdEqual(password,user);
    }
}
